package tree;

/**
 * @author huangliusong
 * @since 2018/10/22
 * {@link }
 */
public class TreeCreater {
    public TreeNode createSample() {
        TreeNode root = new TreeNode('A');
        root.setLeft(new TreeNode('B'));
        root.getLeft().setLeft(new TreeNode('D'));
        root.getLeft().setRight(new TreeNode('E'));
        root.getLeft().getRight().setLeft(new TreeNode('G'));
        root.setRight(new TreeNode('C'));
        root.getRight().setRight(new TreeNode('F'));
        return root;
    }

    //根据后续和中序
    public TreeNode createTreed(String preorder, String inOrder) {
        if (preorder.isEmpty()){
            return null;
        }
        char rootValue = preorder.charAt(0);
        //找到中序遍历的根的位置
        int rootIndex = inOrder.indexOf(rootValue);
        //建立树根
        TreeNode root = new TreeNode(rootValue);
        root.setLeft(createTreed(preorder.substring(1, 1 + rootIndex),
                inOrder.substring(0, rootIndex)));


        root.setRight(createTreed(preorder.substring(1 + rootIndex),
                inOrder.substring(1 + rootIndex)));

        return root;
    }


}
